package com.sx.micowell.framework.model

import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.ToastUtils
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.UserAgreementVO
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction
import com.sx.micowell.framework.tools.EventInfo
import io.reactivex.android.schedulers.AndroidSchedulers

/**
 * @Author: YY
 * @Time: 2021/8/13
 * @Describe
 */
class RegisterToForgetPwdModel : BaseViewModel() {

    override fun registerRxBus() {
        super.registerRxBus()
        addSubscribe(
            RxBus.getDefault().toObservable(EventInfo::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { event ->
                    if (event.type == AppConstant.EVENT_REGISTER_PWD_SUCCESS) {
                        // 注册成功、修改密码成功
                        context.finishEvent.call()
                    }
                }
        )
    }

    // 类型
    var type = 0

    // 手机号码
    var phoneNumber = ObservableField("")

    //是否勾选服务协议
    var isCheckAgreement = ObservableField(false)

    //用户协议数据
    var agreementField: ObservableField<UserAgreementVO> = ObservableField()

    //输入手机号
    var phoneNumberOnTextChangeCommand: BindingCommand<String> = BindingCommand { s ->
        LogUtils.d("phoneNumberOnTextChangeCommand: $s")
        phoneNumber.set(s)
    }

    //是否勾选服务协议
    var isCheckAgreementOnClickCommand: BindingCommand<Boolean> = BindingCommand { isChecked ->
        isCheckAgreement.set(isChecked)
    }

    //点击协议事件
    var agreementOnClickCommand: BindingCommand<IBindingAction> = BindingCommand(IBindingAction {
        val bundle = Bundle()
        bundle.putSerializable(IntentKey.DATA, agreementField.get())
        context.startContainerActivity(
            RouteManager.getInstance().getUserAgreementFragment(agreementField.get()).javaClass.canonicalName, bundle
        )
    })

    // 下一步
    val nextStepOnClickCommand = BindingCommand<Any>(IBindingAction {

        if (TextUtils.isEmpty(phoneNumber.get())) {
            ToastUtils.showShort("请输入手机号")
            return@IBindingAction
        }

        if (type == 0) {
            if (isCheckAgreement.get() != true) {
                ToastUtils.showShort("请阅读并同意用户使用协议")
                return@IBindingAction
            }
        }
        sendSmsCode(type,phoneNumber.get().toString())

    })


    fun sendSmsCode(type: Int, phone: String) {
        if (type == 0 || type == -1) {
            HttpClient.instance.apiService
                .sendRegisterSms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        RouteManager.getInstance().intentVerifyCode(phoneNumber.get().toString(), type)
                        ToastUtils.showShort("$msg")
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        } else {
            HttpClient.instance.apiService
                .sendModifySms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$msg")
                        RouteManager.getInstance().intentVerifyCode(phoneNumber.get().toString(), type)
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        }
    }

    fun setPhoneNum(phone : String) {
        phoneNumber.set(phone)
    }

    /**
     * 用户协议
     */
    fun userAgreement() {

        addSubscribe(
            HttpClient.instance.apiService
                .userAgreement()
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<UserAgreementVO>() {

                    override fun success(data: UserAgreementVO?, msg: String?) {
                        ui.hideDialog()
                        LogUtils.d("userAgreement: ${data?.userAgreement}")
                        agreementField.set(data)
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                    }

                })
        )
    }
}